from multiprocessing import process, Process

from django.shortcuts import render
from django.views import View
from redis.utils import pipeline


from qingmei_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from qingmei_mall.utils.response_code import  RETCODE
from yzm import constants
from ronglian_sms_sdk import SmsSDK
from django import http
import random
class ImageCodeView(View):
    def get (self,request,uuid):
        #接受
        #验证
        #处理
        mark ,code, img=captcha.generate_captcha()
        #保存
        redis_cli=get_redis_connection('imagecode')
        #写入redis setex(key,过期时间,value)
        redis_cli.setex(uuid,constants.IMAGE_CODE_REDIS_EXPIRES,code)
        #xiangyinngpipline
        return http.HttpResponse(img,content_type='image/png')

class SmcodeView(View):
    def get(self,request,mobile):
        #接受
        image_code=request.GET.get('image_code')
        uuid=request.GET.get('image_code_id')

        GetRedis_image=get_redis_connection('imagecode') #连接数据库
        pl=pipeline(GetRedis_image)   #pl.execute()  数据库管道优化
        image_code_redis=GetRedis_image.get(uuid)  #取值


        #验证\
        #短信频繁
        if GetRedis_image.get('lag_'+mobile):
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR,'errmsg':'短信频繁'})
        GetRedis_image.setex('lag_'+mobile,constants.Restrict_REDIS_EXPIRES,'2')

        if not all([image_code,uuid]):
            return http.HttpResponseBadRequest ('参数错误')

        if image_code_redis.decode() != image_code.upper():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码不正确'})
        if image_code_redis is None:
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码为空'})

        #图形过期
        GetRedis_image.delete(uuid)

        #处理
        Random='%06d'%random.randint(1,999999)
        GetRedis_image.setex('sms_'+mobile,constants.CODE_REDIS_EXPIRES,Random)
        accId = '8aaf07087f77bf96017fce173dfe28af'
        accToken = '1b35433e8afd48ecacdea5a15f3b72dc'
        appId = '8aaf07087f77bf96017fcf61036e2aa3'
        sdk = SmsSDK(accId, accToken, appId)

        Pro = Process(target=sdk.sendMessage, args=('1', mobile, (Random, int(constants.CODE_REDIS_EXPIRES / 60))))
        Pro.start()

        # sdk=SmsSDK(accId,accToken,appId)
        # sdk.sendMessage('1',mobile,(Random,int(constants.CODE_REDIS_EXPIRES/60)))
        # send_sms_celery.delay('1',mobile,(Random,int(constants.CODE_REDIS_EXPIRES/60)))
        #相应

        return  http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})


